import {
	enterBig,
	createWS
} from '@/api/index.js'
import {
	messageBody,
	wsSend
} from '../../utils/index.js'
import {
	Ws
} from './model.js'
export default {
	data() {
		return {
			bigId: '',
			meetingId: '',
			waiterId: '',
			bigSocketTask: {},
			socketTask: {},
			wsOpen: false,
			timeout: 5000,
			interval: 3000,
			clientTimer: null,
			severTimer: null,
			chatTimer:null,
			chatStart:null,
			keepTime:180000
		}
	},
  filters:{
      timestamp(val){
        return  new Date(val).toLocaleTimeString()
      }
  },
	watch: {
		wsOpen: { //监听小会场建立成功
			handler(newVal) {
				if (newVal) {
					this.socketTask.onMessage((e) => {
						this.onMessage(e)
					})
				}
			}
		},
	},
	methods: {
		/*创建大会场*/
		creatBigMeeting() {
			const params = {
				userId: this.customId,
				talkerType: "member",
			};
			enterBig(params).then((res) => {
				const {
					data
				} = res
				this.bigId = data
				if (this.bigId) {
					const s = `?talkerType=member&talkerId=${this.customId}&meetingId=${this.bigId}`
					this.createWebsocket(s)
				}
			}).catch(err => {
				throw new Error(`创建大会场接口异常${err}`)
			})
		},
		// ws连接
		async createWebsocket(params) {
			this.bigSocketTask = await createWS(params)
			this.wsListener()
		},
		// ws监听
		wsListener() {
			this.bigSocketTask.onOpen(() => {
				// this.heartStart()
				console.log('连接上了')
			})
			this.bigSocketTask.onMessage((e) => {
				console.log('收到消息', e)
				// this.heartStart()
				let {
					data
				} = e
				const {
					type,
					content
				} = JSON.parse(data)
				if (type === '0x20') { //主会场欢迎辞
					console.log('content')
				}
				if (type === '0x24') { //客服邀请用户
					this.meetingId = content
					const s = `?talkerType=member&talkerId=${this.customId}&meetingId=${this.meetingId}`
					const wsInstance = new Ws(s)
					wsInstance.createWebsocket()
					this.socketTask = wsInstance.socketTask
					this.socketTask.onOpen(() => {
						this.wsOpen = true
						console.log('小会场连接上了')
					})
				}
			})
			this.bigSocketTask.onClose(() => {
				console.log('关闭了大会场')
			})
		},
		heartStart() {
			this.serverTimer && clearTimeout(this.serverTimer);
			this.clientTimer && clearInterval(this.clientTimer);
			this.clientTimer = setInterval(() => {
				//发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
				let params = {
					meetingId: this.meetingId,
					memberId: this.customId,
					waiterId: this.waiterId,
					contentType: 1,
					content: ''
				}
				wsSend(this.bigSocketTask, params)
				//定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
				this.serverTimer = setTimeout(() => {
					this.bigSocketTask.close();
					this.reConnect();
				}, this.timeout);
			}, this.interval);
		},
		reConnect() {
			this.createWebsocket()
		},
		onMessage(e) {
			this.chatStart = new Date().getTime()
			this.meetingTimeout() 
			// this.heartStart()
			let {
				data
			} = e
			const message = JSON.parse(data)
			// 正常消息
			let showData = {}
			let msg = {
				id: message.serial,
				time: message.sTime,
			}
			let params = {}
			if (message.type === '0x27' ) { 
			    this.editTitle(0)
			}
			if (message.type === '0x28' ) {
			    this.editTitle(1)
			}
			if (message.type === '0x30' || message.type === '0x31') { //欢迎、告别辞
				params = {
					type: 'system',
					uid: '9527_',
					content:{text: message.content.word},
					talkType: 'text'
				}
			}
			if (message.type === '0x40') { //文字对话且不是自己说的话
				params = {
					type: 'user',
					uid: message.content.talkerId,
					content:{text: message.content.word},
					talkType: 'text'
				}
			}
			if (message.type === '0x44') { //图片对话且不是自己说的话
				params = {
					type: 'user',
					uid: message.content.talkerId,
					content: {url:message.content.word},
					talkType: 'img'
				}
			}
			showData = messageBody({ ...msg,
				...params
			})
			this.screenMsg(showData);
		},
      // 计时关闭小会场
      meetingTimeout(){
		  this.chatTimer && clearInterval(this.chatTimer) 
		  this.chatTimer = setInterval(()=>{
			 const range = new Date().getTime() - this.chatStart
			 if(range > this.keepTime ){
				 let params = {
				 	contentType:'0x26',
				 	content: '用户静待超时'
				 }
				 wsSend(this.socketTask,params)
				 this.socketTask.close()
				 clearInterval(this.chatTimer)
				 this.$refs.popup.open()
			 } 
		  },1000)
	  },
	  // 更改标题
	  editTitle(event){
	  	if(event == 0) {
	  		uni.setNavigationBarTitle({
	  		　　title:'对方正在输入...'
	  		})
	  	}else{
	  		uni.setNavigationBarTitle({
	  		　　title:'客服咨询'
	  		})
	  	}
	  },
	},

}
